const global = getApp().globalData;
const Api = global.Api;
const wxApi = global.wxApi;
const util = global.util;
const topicApi = global.topicApi;
Page({
  data: {
    bookid: "",
    bookdata: {},
    tabSelected: 1,
    unitsData: [],
    screenHeight: 0,
    links: [],
    openLink: false,
    linkViewTitle: '',
    unitsCount: 0,
    topicsData: [],
    topicsCount: 0,
    showMorePanel: false
  },

  onLoad: function (options) {
    let bookid = options.id;
    this.setData({
      bookid: bookid
    });
    this.needRefresh = true;
    this.logger = global.logger;
  },
  onShow() {
    if (this.needRefresh) {
      let bookid = this.data.bookid;
      this.init( bookid );
      this.needRefresh = false;
    }
    
  },
  init( bookid ) {
    this.parser = require('../../js/parser')
    // 请求课本详情
    this.loadBookDetail( bookid );
    // 请求单元列表
    this.loadBookUnits( bookid );
  },
  selectUnit: function () {
    this.setData({
      tabSelected: 1
    })
  },
  selectIntro: function () {
    this.setData({
      tabSelected: 2
    })
  },
  loadBookDetail( bookid ) {
    Api.getBookDetail(bookid, data => {
      this.logger.info('课本详情', data);
      wxApi.setNavTitle( data.name );
      this.setData({
        bookdata: data
      })
      
      wxApi.getScreenSize( size => {
        let subscribed = this.data.bookdata.subscribed;
        this.setData({
          screenHeight: subscribed ? size.height - 210 : size.height - 260
        })
      } )
    });
  },
  onUnitTap(e) {
    let unit = e.detail;
    let params = {
      unitId: unit.id,
      unitName: unit.name,
      viewId: 'unit' + unit.id,
      subed: this.bookIsSubed()
    }
    this.goTopicsPage(params)
  },
  onLessonTap(e) {
    let unit = e.detail.unit;
    let lessson = e.detail.lesson;
    let params = {
      unitId: unit.id,
      unitName: unit.name,
      lessonId: lessson.id,
      viewId: 'lesson' + lessson.id,
      subed: this.bookIsSubed()
    }
    this.goTopicsPage(params);
  },
  onTopicTap(e) {
    let topic = e.detail;
    topic.viewId = 'topic' + topic.id;
    topic.subed = topic.textbookSubscribed;
    this.goTopicsPage(topic);
  },
  /**
   * 查看更多知识点
   */
  onMoreTopic() {
    let params = {
      unitId: this.unitId,
      unitName: this.unitName,
      lessonId: this.lesssonId,
      subed: this.bookIsSubed()
    }
    this.goTopicsPage(params);
  },
  bookIsSubed() {
    let bookdata = this.data.bookdata;
    return bookdata.subscribed ? 1 : 0;
  },
  /**
   * 跳转知识点列表
   */
  goTopicsPage(params) {
    let path = '../lessons/lessons'
    wxApi.navigateTo(path, params);
  },
  loadTopics(unitId, callback) {
    topicApi.getTopicsByUnitID(unitId, null, data => {
      let topics = data.records;
      
      this.logger.info('知识点列表', topics);
      this.setData({
        topicsData: topics,
        topicsCount: data.total,
        showMorePanel: topics.length === data.pageSize
      })
    });
  },
  loadBookUnits( bookid ) {
    Api.getUnits(bookid, data => {
      this.logger.info('单元列表', data);
      // 只有一个单元一个课文的情况
      if (data.length === 1 && data[0].lessons.length === 1 ) {
        this.singleUnitLessonImp(data[0]);
        return;
      }
      this.setData({
        unitsData: data
      })
    })
  },
  /**
   * 课本只有一个单元一个课文的情况
   */
  singleUnitLessonImp(unit) {
    this.setData({
      unitsCount: 1
    })
    this.unitId = unit.id;
    this.unitName = unit.name;
    this.lessonId = unit.lessons[0].id;
    this.loadTopics(unit.id);
  },
  /**
   * 相关一课一练和试卷
   */
  onOpenRelated(type) {
    this.setData({
      openLink: true
    })
    if (type === 'practice') {
      this.setData({
        title: '附赠一课一练',
        links: this.data.bookdata.workbooks
      })
    } else if (type === 'paper') {
      this.setData({
        title: '附赠相关试卷',
        links: this.data.bookdata.papers
      })
    }
  },
  onLinkTap(e) {
    let linkObj = e.detail;
    wxApi.navigateTo('../common/nonsupport/nonsupport', {
      path: 'exercise',
      module: 'detail',
      type: linkObj.type,
      practiceId: linkObj.id
    })
  },
  onSubscribe() {
    let bookData = this.data.bookdata;
    if (bookData.preferentialPrice == 0) {
      this.createBeansOrder();
    } else {
      let book = util.encodeURI( bookData );
      let path = '../common/buy-goods/buy-goods'
      wxApi.navigateTo(path, {
        data: book,
        type: 0
      });
    }
    
  },
  createBeansOrder() {
    let bookData = this.data.bookdata;
    let params = {
      'textbookId': bookData.id
    }
    if ( this.paying ) {
      return;
    }
    this.paying = true;
    Api.createOrders( params, res => {
      console.log( res );
      if (res === null) {
        wxApi.navigateTo( '../common/buy-result/buy-result', {
          type: 'success'
        })
        return;
      }
      let outTradeNo = res.outTradeNo;
      this.studyBeansBuyFlow(outTradeNo);
    } )
  },
  studyBeansBuyFlow(outTradeNo) {
    Api.createStudyBeansOrder(outTradeNo, (res, code) => {
      if (code == 0) {
        wxApi.navigateTo( '../common/buy-result/buy-result', {
          type: 'success',
          backCount: 1
        })
      } else {
        wxApi.navigateTo( '../common/buy-result/buy-result', {
          type: 'fail',
          backCount: 1
        })
      }
    })
  }
}) 